<?php
namespace Biz\service;

use Biz\model\ShopAdorn as mShopAdorn;
use Biz\model\ShopSwitch;
use Common\Lib\Log;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Log as tLog;
/**
 * @deprecated
 */
class ShopAdorn
{

	const LINK_MALL_SHOP_GOODS_LIST = "hhz://mall_shop_goods_list:{\"shop_id\":%d,\"sort_type\":0,\"filter_id\":%d}";

	const LINK_MALL_GOODS_ID = "hhz://mall_goods_id:%d";

	/**
	 * 店铺装修 添加 单图, 多图轮播
	 * @param $shop_id
	 * @param $banner_order
	 * @param array $banner_info
	 */
	public static function addAdornPic($shop_id, $banner_order, array $banner_info)
	{
		tLog::debug('addAdorn', [
			'shop_id' => $shop_id,
			'banner_order' => $banner_order,
			'banner_info' => $banner_info
		]);
		self::checkBannerInfo($shop_id, $banner_info);
		if (isset($banner_info[0])) {
			//添加多图轮播
			self::addMutiPicAdorn($shop_id, $banner_order, $banner_info);
		} else {
			//添加单图banner
			self::addSinglePic($shop_id, $banner_order, $banner_info);
		}
	}

	/**
	 * 编辑单个banner 图片信息
	 *
	 * @param $shop_id
	 * @param $banner_id
	 * @param array $banner_info
	 * @throws \Exception
	 */
	public static function editAdornPic($shop_id, $banner_id, $banner_order, array $banner_info)
	{
		tLog::debug('editAdorn', [
			'shop_id' => $shop_id,
			'banner_id' => $banner_id,
			'banner_order' => $banner_order,
			'banner_info' => $banner_info
		]);
		self::checkBannerInfo($shop_id, $banner_info);

		if (isset($banner_info[0])) {
			$is_multi_pic_grp_id = mShopAdorn::isOwnerPicGrpId($shop_id, $banner_id);
			if (!$is_multi_pic_grp_id) {
				tLog::warning($shop_id, ['banner_id' => $banner_id, 'banner_info' => $banner_info]);
				throw new \Exception('不可修改');
			}

			$currentIds = [];
			$insertData = [];
			self::editMultiPicAdorn($currentIds, $insertData, $shop_id, $banner_id, $banner_order, $banner_info);

			$map = [];
			if ($currentIds) {
				$map['id[!]'] = $currentIds;
			}
			$map['uid'] = $shop_id;
			$map['pic_group_id'] = $banner_id;
			$map['status'] = mShopAdorn::STATUS_NORMAL;
			mShopAdorn::updateData([
				'status' => mShopAdorn::STATUS_DEL
			], $map);

			mShopAdorn::addMultiPic($insertData);

		} else {


            self::resetBannerOrder($shop_id, $banner_order, $banner_id, 'update');

            mShopAdorn::updateData([
                'pic_id' => $banner_info['pic_id'],
                'link_type' => $banner_info['link_type'],
                'link_target' => $banner_info['link_target'],
                'banner_order' => $banner_order,
            ], [
                'id' => $banner_id,
                'status' => mShopAdorn::STATUS_NORMAL
            ]);
        }

    }

	public static function adornSwitch($shopId, $adornType, $isSwitch)
    {
        if (in_array($isSwitch, [ ShopSwitch::SWITCH_ON, ShopSwitch::SWITCH_OFF]) && in_array($adornType, [
                ShopSwitch::TYPE_HOT_GOODS, ShopSwitch::TYPE_COUPON
            ])) {
            $switchInfo = ShopSwitch::getInfo($shopId);
            if ($switchInfo) {
                ShopSwitch::updateData($shopId, [ShopSwitch::MAP_TYPE_FIELDS[$adornType] => $isSwitch]);
            } else {
                ShopSwitch::insertData($shopId, [ShopSwitch::MAP_TYPE_FIELDS[$adornType] => $isSwitch]);
            }
        } else {
            throw new \Exception('请检查数据');
        }
        return true;
    }

	/**
	 *
	 *
	 * 获取单个banner 图片信息
	 * @param $uid
	 * @param $banner_id
	 * @return array
	 *
	 */
	public static function getBannerInfo($uid, $banner_id)
	{
		$filter = [];
		$returnRst = [];
		if (mShopAdorn::isPicGrpId($banner_id)) {
			$filter['pic_group_id'] = $banner_id;
			$multiPics = mShopAdorn::getInfo($uid, $filter);
			$returnRst['pre_banner_id'] = $multiPics[0]['prev_id'];
			$returnRst['banner_info'] = [];
			foreach ($multiPics as $info) {
				$returnRst['banner_info'][] = [
					'id' => $info['pic_group_id'],
					'pic_id' => $info['pic_id'],
					'pic_url' => ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $info['pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI),
					'link_type' => $info['link_type'],
					'link_target' => $info['link_target'],
					'order' => $info['order'],
				];
			}

		} else {

			$filter['id'] = $banner_id;
			$info = mShopAdorn::getInfo($uid, $filter)[0];
			$returnRst['pre_banner_id'] = $info['prev_id'];

			$returnRst['banner_info'] = $info ? [
				'id' => $info['id'],
				'pic_id' => $info['pic_id'],
				'pic_url' => ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $info['pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI),
				'link_type' => $info['link_type'],
				'link_target' => $info['link_target'],
			] : [];
		}

		return $returnRst;

	}


	/**
	 *
	 * 删除单个 banner
	 * @param $shop_id
	 * @param $banner_id
	 */
	public static function delBanner($shop_id, $banner_id)
	{
		$isPicGrpId = mShopAdorn::isPicGrpId($banner_id);


		$map = [];
		if ($isPicGrpId) {
			$map['pic_group_id'] = $banner_id;
		} else {
			$map['id'] = $banner_id;
		}
		$infos = mShopAdorn::getInfo($shop_id, $map);
		$banner_id = $infos[0]['id'] ? $infos[0]['id'] : $infos[0]['pic_group_id'];
		$banner_order = $infos[0]['banner_order'];

		self::resetBannerOrder($shop_id, $banner_order, $banner_id, 'delete');

		mShopAdorn::updateData([
			'status' => mShopAdorn::STATUS_DEL,


		], $map);

	}



	public static function shopPageAdorn($shop_id)
	{
		$AdornList = self::getAllBannerList($shop_id);

		$Rst = [];
		foreach ($AdornList as $k => $Adorn) {
			if (mShopAdorn::isPicGrpId($k)) {
				$Rst[] = [
					'id' => $k,
					'banner_list' => array_map(function ($info) use ($shop_id) {
						return [
							'link_type' => $info['link_type'],
							'link' => $info['link_type'] == mShopAdorn::LINK_TYPE_MULTIPIC  ?
								sprintf(self::LINK_MALL_SHOP_GOODS_LIST, $shop_id, $info['id'])
								:
								(
								$info['link_type'] == mShopAdorn::LINK_TYPE_NORLINK ?
									''
									:
									sprintf(self::LINK_MALL_GOODS_ID, $info['link_target'])
								),
							'banner' => ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $info['pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI),
						];
					}, $Adorn)
				];
			} else {
				$Rst[] = [
					'id' => $k,
					'banner_list' => [[
						'link_type' => $Adorn['link_type'],
						'link' => $Adorn['link_type'] == mShopAdorn::LINK_TYPE_MULTIPIC ?
							sprintf(self::LINK_MALL_SHOP_GOODS_LIST, $shop_id, $Adorn['id'])
							:
							(
								$Adorn['link_type'] == mShopAdorn::LINK_TYPE_NORLINK  ?
									''
									:
									sprintf(self::LINK_MALL_GOODS_ID, $Adorn['link_target'])
							),
						'banner' => ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $Adorn['pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI),
					]]
				];

			}

		}

		return $Rst;

	}



	private static function getAllBannerList($shop_id)
	{
		$Adorninfos = mShopAdorn::getInfo($shop_id);

		$AdornList = [];
		foreach ($Adorninfos as $adorn) {
			if ($adorn['pic_group_id'] && mShopAdorn::isPicGrpId($adorn['pic_group_id'])) {
				$AdornList[$adorn['pic_group_id']][] = $adorn;
			} else {
				$AdornList[$adorn['id']] = $adorn;
			}
		}

		return $AdornList;

	}

	public static function admShopPageAdorn($shop_id)
	{
		$AdornList = self::getAllBannerList($shop_id);

		$Rst = [];
		foreach ($AdornList as $id => $AdornInfo) {
			if (mShopAdorn::isPicGrpId($id)) {
				$Rst[] = self::formatMulti($AdornInfo);
			} else {
				$Rst[] = self::formatSingle($AdornInfo);
			}
		}


		return $Rst;

	}

	private static function formatMulti($adornList)
	{

		return [
			'banner_id' => $adornList[0]['pic_group_id'],
			'banner_order' => $adornList[0]['banner_order'],
			'banner_info' => array_map(function ($adorn){
				return [
					'id' => $adorn['id'],
					'pic_id' => $adorn['pic_id'],
					'link_type' => $adorn['link_type'],
					'link_target' => $adorn['link_target'],
					'order' => $adorn['order'],
					'banner' => ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $adorn['pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI),
				];
			}, $adornList)
		];

	}

	private static function formatSingle($adornInfo)
	{
		return [
			'banner_id' => $adornInfo['id'],
			'banner_order' => $adornInfo['banner_order'],
			'banner_info' => [
				'id' => $adornInfo['id'],
				'pic_id' => $adornInfo['pic_id'],
				'banner' => ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $adornInfo['pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI),
				'link_type' => $adornInfo['link_type'],
				'link_target' => $adornInfo['link_target'],
				'order' => $adornInfo['order'],

			]
		];
	}




	private static function editMultiPicAdorn(&$currentIds , &$insertData, $shop_id, $banner_id, $banner_order, $banner_info)
	{

		self::resetBannerOrder($shop_id, $banner_order, $banner_id, 'update');

		foreach ($banner_info as $banner) {
			if (isset($banner['id'])) {
				$currentIds[] = $banner['id'];

				mShopAdorn::updateData([
					'pic_id' => $banner['pic_id'],
					'link_type' => $banner['link_type'],
					'link_target' => $banner['link_target'],
					'banner_order' => $banner_order,
					'order' => $banner['order'],
				], [
					'id' => $banner['id'],
					'uid' => $shop_id,
					'pic_group_id' => $banner_id
				]);

			} else {
				$insertData[] = [
					'uid' => $shop_id,
					'pic_id' => $banner['pic_id'],
					'pic_group_id' => $banner_id,
					'banner_order' => $banner_order,
					'link_type' => $banner['link_type'],
					'link_target' => $banner['link_target'],
					'order' => $banner['order'],
				];
			}
		}
	}

	/**
	 *
	 * @param $shop_id
	 * @param $pre_banner_id
	 * @param array $banner_info
	 */
	private static function addSinglePic($shop_id, $banner_order, array $banner_info)
	{
		$insertData = [
			'uid' => $shop_id,
			'pic_id' =>  $banner_info['pic_id'],
			'link_target' => (string) isset($banner_info['link_target']) ? $banner_info['link_target'] : '',
			'link_type' => (integer) isset($banner_info['link_type']) ? $banner_info['link_type'] : 0,
			'banner_order' => $banner_order,
		];

		self::resetBannerOrder($shop_id, $banner_order, '', 'add');
		$currentId = mShopAdorn::addSinglePic($insertData);
		tLog::debug('addsingle_pic', ['id' => $currentId]);

	}

	/**
	 * 添加轮播图
	 * @param $pre_bannere_id //排序字段 上一个banner id
	 * @param array $banner_info
	 */
	private static function addMutiPicAdorn($shop_id, $banner_order, array $banner_info)
	{
		$MutiPicGrpID = mShopAdorn::createPicGrpId($shop_id);

		$intertData = array_map(function ($banner) use ($shop_id, $MutiPicGrpID, $banner_order) {
			return [
				'pic_group_id' => $MutiPicGrpID,
				'uid' => $shop_id,
				'pic_id' => $banner['pic_id'],
				'link_target' => $banner['link_target'],
				'banner_order' => $banner_order,
				'link_type' => $banner['link_type'],
				'order' => $banner['order'],
			];
		}, $banner_info);


		self::resetBannerOrder($shop_id, $banner_order, '', 'add');
		mShopAdorn::addMultiPic($intertData);
	}

	private static function resetBannerOrder($shop_id, $currentOrder, $banner_id = '', $scene = 'add')
	{
		$map['uid'] = $shop_id;
		switch ($scene){
			case 'add' :
				$map['banner_order[>=]'] = $currentOrder;
				break;
			case 'update' :
				$filter = [];
				if (mShopAdorn::isPicGrpId($banner_id)) {
					$filter['pic_group_id'] = $banner_id;
				} else {
					$filter['id'] = $banner_id;
				}
				$infos = mShopAdorn::getInfo($shop_id, $filter);
				$originOrder = $infos[0]['banner_order'];
				$map['banner_order'] = range($originOrder, $currentOrder);
				break;
			case 'delete':
				$map['banner_order[>=]'] = $currentOrder;
				break;
		}

		tLog::debug('resetorder', $map);

		if (in_array($scene, ['add', 'update'])) {
			if ($scene == 'update' && ($originOrder < $currentOrder)) {

				mShopAdorn::updateData([ 'banner_order[-]' => 1, ],$map);

				return '';
			}

			mShopAdorn::updateData([ 'banner_order[+]' => 1, ],$map);

		}

		if (in_array($scene, ['delete'])) mShopAdorn::updateData(['banner_order[-]' => 1], $map);




	}


	public static function SwitchHotGoods($shopID, $status)
	{
		$info = ShopSwitch::getInfo($shopID);


		if ($info) {
			return ShopSwitch::updateData($shopID, ['is_show_hotgoods' => $status]);
		}

		return ShopSwitch::insertData($shopID, ['is_show_hotgoods' => $status]);

	}

	private static function checkBannerInfo($shop_id, &$bannerInfo)
	{
		if (isset($bannerInfo[0])) {

			foreach ($bannerInfo as &$info) {
				self::checkLinkTarget($shop_id, $info['link_type'] , $info['link_target']);
			}

		} else {
			self::checkLinkTarget($shop_id, $bannerInfo['link_type'] , $bannerInfo['link_target']);
		}

	}

	private static function checkLinkTarget($shopId ,$link_type, &$link_target)
	{
		$is_check_goods = true;
		if ($link_type == mShopAdorn::LINK_TYPE_SIGLEPIC) {
			$goodsIds = [$link_target];
		} elseif ($link_type == mShopAdorn::LINK_TYPE_MULTIPIC) {
			$link_target = preg_replace("/[^\d]/", ",", $link_target);
			$goodsIds = array_filter( explode(',', $link_target) ) ;
			$link_target = implode(',', $goodsIds);
		} elseif($link_type == mShopAdorn::LINK_TYPE_NORLINK){
			$is_check_goods = false;
		} else {

			throw new \Exception('link_type 类型错误');
		}

		if ($is_check_goods && ( empty($goodsIds) || !(self::is_int($goodsIds) && self::is_ownerGoods($shopId, $goodsIds)))) {
			throw new \Exception('请输入正确的商品ID');
		}

	}

	private static function is_int(array $goodsIds)
	{
		foreach ($goodsIds as $goodsId) {
			if (!is_numeric($goodsId)) {
				return false;
			}
		}

		return true;
	}

	private static function is_ownerGoods($shop_id, array $goods_ids)
	{
		$goodDetails = GoodsDetail::formatBasicInfos($goods_ids);
		if (array_diff($goods_ids, array_keys($goodDetails))) {
			throw new \Exception('存在无效的商品ID');
		}

		foreach ($goodDetails  as $goodDetail) {
			if ($goodDetail['shop_info']['shop_id'] != $shop_id) {
				return false;
			}
		}

		return true;
	}


}